#include "CommonFile.h"

CCommonFile::CCommonFile() : 
							 m_DataInFile(NULL)
{
	
}


CCommonFile::~CCommonFile()
{
	delete[] m_DataInFile;
}

int CCommonFile::GetSizeFile(char *fileName)
{
#ifdef mode
	if (m_file.is_open())
		m_file.close();

	m_file.open(fileName);
	if(!this->m_file)
		return -1;

	m_file.seekg(0, m_file.end);
	m_size = m_file.tellg();
	m_file.seekg (0, m_file.beg);
	
	return this->m_size;
#else
	m_file = fopen(fileName, "rb");
	if (!this->m_file)
		return -1;									// this is FALSE

	fseek(m_file, 0, SEEK_END);						// move pointer go to end of file
	m_size = ftell(m_file);
	fseek(m_file, 0, SEEK_SET);						// come back  head of file

	fclose(m_file);
	return this->m_size;
#endif
}

char* CCommonFile::ReadDataFromFile(char* fileName)
{
#ifdef mode
	GetSizeFile(fileName);
	
	this->m_fileName = fileName;
	if(this->m_file.is_open())
		m_file.close();

	this->m_file.open(m_fileName);
	if(!this->m_file)
		return false;

	m_DataInFile = new char[m_size];

	m_file.read(m_DataInFile, m_size);
	

	m_file.close();
	return m_DataInFile;

#else
	GetSizeFile(fileName);   

	this->m_fileName = fileName;
	if (!this->m_file)
		fclose(m_file);

	this->m_file = fopen(this->m_fileName, "rb");

	if (!this->m_file)
		return false;								// this is FALSE

	// get size of file
	
	m_DataInFile = new char[m_size];
	fread(m_DataInFile, m_size, 1, m_file);		// read all data in a file;

	fclose(m_file);

	return m_DataInFile;
#endif
}

int CCommonFile::WriteDataToFile(char* fileName)
{
#ifdef mode
	if (this->m_file.is_open())
		m_file.close();
	
	this->m_fileName = fileName;
	
	m_file.open(m_fileName);
	if (!this->m_file)
		return false;
	m_file.write(m_DataInFile, m_size);
	m_file.close();

#else
	if (this->m_file)
		fclose(m_file);

	this->m_fileName = fileName;

	m_file = fopen(m_fileName, "wb");
	if (!this->m_file)
		return false;

	fwrite(m_DataInFile, m_size, 1, m_file);
	fclose(m_file);
#endif
}

int CCommonFile::WriteDataToFile(char* data, char* fileName)
{
#ifdef mode
	if (this->m_file.is_open())
		m_file.close();

	this->m_fileName = fileName;

	m_file.open(m_fileName);
	if (!this->m_file)
		return false;
	m_DataInFile = data;
	
	m_file.write(m_DataInFile, m_size);
	m_file.close();
#else
	if (this->m_file)
		fclose(m_file);

	this->m_fileName = fileName;

	m_file = fopen(m_fileName, "wb");
	if (!this->m_file)
		return false;
	m_DataInFile = data;

	fwrite(m_DataInFile, m_size, 1, m_file);
	fclose(m_file);
#endif
}

char* CCommonFile::GetData()
{
	return m_DataInFile;
}